<template>
  <view class="task-management-container">
    <!-- 自定义导航栏 -->
    <cu-custom bgColor="bg-gradual-blue" :isBack="true">
      <block slot="content">任务管理</block>
      <block slot="right">
        <text class="cuIcon-add" @click="createTask"></text>
      </block>
    </cu-custom>

    <!-- 统计概览 -->
    <view class="stats-overview margin-top bg-white">
      <view class="stats-grid padding">
        <view class="stat-item" @click="filterByStatus('all')">
          <view class="stat-number text-blue">{{ taskStats.total }}</view>
          <view class="stat-label">总任务</view>
        </view>
        <view class="stat-item" @click="filterByStatus('pending')">
          <view class="stat-number text-orange">{{ taskStats.pending }}</view>
          <view class="stat-label">待分配</view>
        </view>
        <view class="stat-item" @click="filterByStatus('in_progress')">
          <view class="stat-number text-green">{{ taskStats.inProgress }}</view>
          <view class="stat-label">进行中</view>
        </view>
        <view class="stat-item" @click="filterByStatus('completed')">
          <view class="stat-number text-purple">{{ taskStats.completed }}</view>
          <view class="stat-label">已完成</view>
        </view>
      </view>
    </view>

    <!-- 搜索和筛选 -->
    <view class="search-filter margin-top bg-white">
      <view class="search-bar padding">
        <view class="search-input-wrapper">
          <input v-model="searchKeyword" 
                 placeholder="搜索任务名称或工种" 
                 class="search-input" 
                 @input="onSearch" />
          <text class="cuIcon-search search-icon"></text>
        </view>
      </view>
      <view class="filter-tabs padding-lr">
        <scroll-view scroll-x class="filter-scroll">
          <view class="filter-tab-list">
            <view v-for="tab in filterTabs" :key="tab.value"
                  class="filter-tab" 
                  :class="{ active: currentFilter === tab.value }"
                  @click="changeFilter(tab.value)">
              {{ tab.label }}
            </view>
          </view>
        </scroll-view>
      </view>
    </view>

    <!-- 任务列表 -->
    <view class="task-list margin-top">
      <view v-for="task in filteredTasks" :key="task.id" 
            class="task-item bg-white margin-bottom" 
            @click="viewTaskDetail(task)">
        <view class="task-header padding">
          <view class="flex justify-between align-center">
            <view class="task-title">{{ task.title }}</view>
            <view class="task-priority" :class="task.priorityClass">
              {{ task.priorityText }}
            </view>
          </view>
          <view class="task-meta margin-top-sm">
            <text class="text-sm text-gray">计划：{{ task.planName }}</text>
            <text class="text-sm text-gray margin-left">工种：{{ task.workType }}</text>
          </view>
        </view>
        
        <view class="task-content padding-lr">
          <view class="task-progress margin-bottom-sm">
            <view class="flex justify-between align-center margin-bottom-xs">
              <text class="text-sm">进度</text>
              <text class="text-sm">{{ task.progress }}%</text>
            </view>
            <view class="progress-bar">
              <view class="progress-fill" :style="{ width: task.progress + '%' }"></view>
            </view>
          </view>
          
          <view class="task-assignment flex align-center margin-bottom-sm">
            <text class="text-sm text-gray">负责人：</text>
            <view v-if="task.assignedEmployee" class="employee-info flex align-center">
              <image :src="task.assignedEmployee.avatar || '/static/images/default-avatar.png'" 
                     class="employee-avatar"></image>
              <text class="text-sm margin-left-xs">{{ task.assignedEmployee.name }}</text>
            </view>
            <text v-else class="text-sm text-gray">未分配</text>
          </view>
          
          <view class="task-time flex justify-between text-sm text-gray">
            <text>开始：{{ formatTime(task.startTime) }}</text>
            <text>截止：{{ formatTime(task.endTime) }}</text>
          </view>
        </view>

        <!-- 操作按钮 -->
        <view class="task-actions padding">
          <view class="action-buttons flex gap-sm">
            <button v-if="!task.assignedEmployee" 
                    class="cu-btn sm bg-blue" 
                    @click.stop="assignTask(task)">
              分配任务
            </button>
            <button v-if="task.assignedEmployee && task.status === 'pending'" 
                    class="cu-btn sm bg-green" 
                    @click.stop="startTask(task)">
              启动任务
            </button>
            <button class="cu-btn sm bg-gray line" 
                    @click.stop="editTask(task)">
              编辑
            </button>
            <button v-if="task.status !== 'completed'" 
                    class="cu-btn sm bg-red line" 
                    @click.stop="deleteTask(task)">
              删除
            </button>
          </view>
        </view>
      </view>
    </view>

    <!-- 空状态 -->
    <view v-if="filteredTasks.length === 0" class="empty-state text-center padding">
      <text class="cuIcon-list text-gray" style="font-size: 120rpx;"></text>
      <view class="text-gray margin-top">暂无任务</view>
    </view>

    <!-- 任务分配弹窗 -->
    <view v-if="showAssignModal" class="assign-modal" @click="showAssignModal = false">
      <view class="assign-content" @click.stop>
        <view class="assign-header padding">
          <text class="text-lg text-bold">分配任务</text>
          <text class="cuIcon-close float-right" @click="showAssignModal = false"></text>
        </view>
        <view class="employee-list">
          <view v-for="employee in availableEmployees" :key="employee.id"
                class="employee-item padding"
                :class="{ selected: selectedEmployee && selectedEmployee.id === employee.id }"
                @click="selectEmployee(employee)">
            <view class="flex align-center">
              <image :src="employee.avatar || '/static/images/default-avatar.png'" 
                     class="employee-avatar margin-right"></image>
              <view class="flex-sub">
                <view class="employee-name">{{ employee.name }}</view>
                <view class="employee-skills text-sm text-gray">
                  技能：{{ employee.workTypes.join('、') }}
                </view>
              </view>
              <view v-if="selectedEmployee && selectedEmployee.id === employee.id" class="selected-icon">
                <text class="cuIcon-check text-green"></text>
              </view>
            </view>
          </view>
        </view>
        <view class="assign-actions padding">
          <button class="cu-btn bg-gray margin-right" @click="showAssignModal = false">取消</button>
          <button class="cu-btn bg-blue" @click="confirmAssign" :disabled="!selectedEmployee">确认分配</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import mesApi from '../../../api/mes'

export default {
  data() {
    return {
      searchKeyword: '',
      currentFilter: 'all',
      filterTabs: [
        { label: '全部', value: 'all' },
        { label: '待分配', value: 'unassigned' },
        { label: '待开始', value: 'pending' },
        { label: '进行中', value: 'in_progress' },
        { label: '已完成', value: 'completed' }
      ],
      taskStats: {
        total: 0,
        pending: 0,
        inProgress: 0,
        completed: 0
      },
      tasks: [],
      filteredTasks: [],
      showAssignModal: false,
      selectedTask: null,
      selectedEmployee: null,
      availableEmployees: []
    }
  },

  onLoad() {
    this.loadTasks()
  },

  onPullDownRefresh() {
    this.loadTasks().then(() => {
      uni.stopPullDownRefresh()
    })
  },

  methods: {
    async loadTasks() {
      try {
        uni.showLoading({ title: '加载中...' })
        
        const response = await mesApi.productionTask.getList()
        this.tasks = response.data.map(task => ({
          ...task,
          priorityClass: this.calculatePriorityClass(task.priority),
          priorityText: this.calculatePriorityText(task.priority)
        }))
        
        this.calculateStats()
        this.filterTasks()
        
      } catch (error) {
        console.error('加载任务失败:', error)
        this.loadMockData()
      } finally {
        uni.hideLoading()
      }
    },

    loadMockData() {
      this.tasks = [
        {
          id: 1,
          title: '门框切割任务',
          planName: '订单WK001生产计划',
          workType: '切割',
          priority: 'high',
          status: 'pending',
          progress: 0,
          assignedEmployee: null,
          startTime: '2024-03-01 08:00',
          endTime: '2024-03-01 18:00',
          priorityClass: 'priority-high',
          priorityText: '高优先级'
        },
        {
          id: 2,
          title: '窗扇组装任务',
          planName: '订单WK002生产计划',
          workType: '组装',
          priority: 'medium',
          status: 'in_progress',
          progress: 65,
          assignedEmployee: {
            id: 1,
            name: '张三',
            avatar: ''
          },
          startTime: '2024-03-01 09:00',
          endTime: '2024-03-01 17:00',
          priorityClass: 'priority-medium',
          priorityText: '中优先级'
        }
      ]
      
      this.calculateStats()
      this.filterTasks()
    },

    calculateStats() {
      this.taskStats = {
        total: this.tasks.length,
        pending: this.tasks.filter(t => t.status === 'pending').length,
        inProgress: this.tasks.filter(t => t.status === 'in_progress').length,
        completed: this.tasks.filter(t => t.status === 'completed').length
      }
    },

    calculatePriorityClass(priority) {
      const priorityMap = {
        'low': 'priority-low',
        'medium': 'priority-medium',
        'high': 'priority-high'
      }
      return priorityMap[priority] || 'priority-medium'
    },

    calculatePriorityText(priority) {
      const priorityMap = {
        'low': '低优先级',
        'medium': '中优先级',
        'high': '高优先级'
      }
      return priorityMap[priority] || '中优先级'
    },

    onSearch() {
      this.filterTasks()
    },

    changeFilter(filter) {
      this.currentFilter = filter
      this.filterTasks()
    },

    filterByStatus(status) {
      this.currentFilter = status
      this.filterTasks()
    },

    filterTasks() {
      let filtered = this.tasks

      // 搜索过滤
      if (this.searchKeyword.trim()) {
        const keyword = this.searchKeyword.toLowerCase()
        filtered = filtered.filter(task => 
          task.title.toLowerCase().includes(keyword) ||
          task.workType.toLowerCase().includes(keyword)
        )
      }

      // 状态过滤
      if (this.currentFilter !== 'all') {
        if (this.currentFilter === 'unassigned') {
          filtered = filtered.filter(task => !task.assignedEmployee)
        } else {
          filtered = filtered.filter(task => task.status === this.currentFilter)
        }
      }

      this.filteredTasks = filtered
    },

    viewTaskDetail(task) {
      uni.navigateTo({
        url: `/pages/production/task/detail?id=${task.id}`
      })
    },

    createTask() {
      uni.navigateTo({
        url: '/pages/production/task/create'
      })
    },

    editTask(task) {
      uni.navigateTo({
        url: `/pages/production/task/edit?id=${task.id}`
      })
    },

    async assignTask(task) {
      this.selectedTask = task
      this.selectedEmployee = null
      
      try {
        // 获取可分配的员工列表
        const response = await mesApi.employee.getList({
          workType: task.workType,
          status: 'available'
        })
        this.availableEmployees = response.data
      } catch (error) {
        // 模拟数据
        this.availableEmployees = [
          {
            id: 1,
            name: '张三',
            avatar: '',
            workTypes: ['切割', '组装']
          },
          {
            id: 2,
            name: '李四',
            avatar: '',
            workTypes: ['切割', '打包']
          }
        ]
      }
      
      this.showAssignModal = true
    },

    selectEmployee(employee) {
      this.selectedEmployee = employee
    },

    async confirmAssign() {
      if (!this.selectedEmployee) return

      try {
        uni.showLoading({ title: '分配中...' })
        
        await mesApi.productionTask.assign(this.selectedTask.id, {
          employeeId: this.selectedEmployee.id
        })
        
        uni.showToast({
          title: '分配成功',
          icon: 'success'
        })
        
        this.showAssignModal = false
        this.loadTasks()
        
      } catch (error) {
        console.error('分配失败:', error)
        uni.showToast({
          title: '分配失败',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    },

    async startTask(task) {
      try {
        await mesApi.productionTask.start(task.id)
        uni.showToast({
          title: '任务已启动',
          icon: 'success'
        })
        this.loadTasks()
      } catch (error) {
        uni.showToast({
          title: '操作失败',
          icon: 'none'
        })
      }
    },

    async deleteTask(task) {
      uni.showModal({
        title: '确认删除',
        content: '确定要删除这个任务吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              await mesApi.productionTask.delete(task.id)
              uni.showToast({
                title: '删除成功',
                icon: 'success'
              })
              this.loadTasks()
            } catch (error) {
              uni.showToast({
                title: '删除失败',
                icon: 'none'
              })
            }
          }
        }
      })
    },

    formatTime(timeStr) {
      if (!timeStr) return '--'
      const date = new Date(timeStr)
      return `${date.getMonth() + 1}/${date.getDate()} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
    }
  }
}
</script>

<style lang="scss" scoped>
.task-management-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.stats-overview {
  border-radius: 12rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
  margin: 0 24rpx;
  
  .stats-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 24rpx;
    
    .stat-item {
      text-align: center;
      
      .stat-number {
        font-size: 32rpx;
        font-weight: bold;
        margin-bottom: 8rpx;
      }
      
      .stat-label {
        font-size: 24rpx;
        color: #666;
      }
    }
  }
}

.search-filter {
  border-radius: 12rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
  margin: 0 24rpx;
  
  .search-input-wrapper {
    position: relative;
    
    .search-input {
      width: 100%;
      height: 80rpx;
      padding: 0 60rpx 0 24rpx;
      border: 1rpx solid #d9d9d9;
      border-radius: 8rpx;
      font-size: 28rpx;
    }
    
    .search-icon {
      position: absolute;
      right: 24rpx;
      top: 50%;
      transform: translateY(-50%);
      color: #999;
    }
  }
  
  .filter-scroll {
    white-space: nowrap;
    
    .filter-tab-list {
      display: inline-flex;
      
      .filter-tab {
        padding: 16rpx 24rpx;
        margin-right: 16rpx;
        border-radius: 20rpx;
        background-color: #f0f0f0;
        color: #666;
        font-size: 24rpx;
        white-space: nowrap;
        
        &.active {
          background-color: #1890ff;
          color: white;
        }
      }
    }
  }
}

.task-list {
  margin: 0 24rpx;
  
  .task-item {
    border-radius: 12rpx;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
    
    .task-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
    
    .task-priority {
      padding: 8rpx 16rpx;
      border-radius: 16rpx;
      font-size: 24rpx;
      
      &.priority-low {
        background-color: #f6ffed;
        color: #52c41a;
      }
      
      &.priority-medium {
        background-color: #fff7e6;
        color: #fa8c16;
      }
      
      &.priority-high {
        background-color: #fff1f0;
        color: #f5222d;
      }
    }
    
    .progress-bar {
      height: 8rpx;
      background-color: #f0f0f0;
      border-radius: 4rpx;
      overflow: hidden;
      
      .progress-fill {
        height: 100%;
        background-color: #1890ff;
        transition: width 0.3s ease;
      }
    }
    
    .employee-avatar {
      width: 48rpx;
      height: 48rpx;
      border-radius: 50%;
    }
    
    .action-buttons {
      .cu-btn {
        flex: 1;
        margin-right: 16rpx;
        
        &:last-child {
          margin-right: 0;
        }
      }
    }
  }
}

.assign-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 999;
  display: flex;
  align-items: center;
  justify-content: center;
  
  .assign-content {
    background-color: white;
    border-radius: 12rpx;
    margin: 0 48rpx;
    width: calc(100% - 96rpx);
    max-height: 80vh;
    overflow: hidden;
    
    .assign-header {
      border-bottom: 1rpx solid #f0f0f0;
      position: relative;
      
      .cuIcon-close {
        position: absolute;
        right: 0;
        top: 50%;
        transform: translateY(-50%);
        font-size: 32rpx;
        color: #999;
      }
    }
    
    .employee-list {
      max-height: 60vh;
      overflow-y: auto;
      
      .employee-item {
        border-bottom: 1rpx solid #f0f0f0;
        
        &:last-child {
          border-bottom: none;
        }
        
        &.selected {
          background-color: #e6f7ff;
        }
        
        .employee-avatar {
          width: 60rpx;
          height: 60rpx;
          border-radius: 50%;
        }
        
        .employee-name {
          font-size: 28rpx;
          font-weight: bold;
          margin-bottom: 4rpx;
        }
        
        .selected-icon {
          font-size: 32rpx;
        }
      }
    }
    
    .assign-actions {
      border-top: 1rpx solid #f0f0f0;
      display: flex;
      gap: 16rpx;
      
      .cu-btn {
        flex: 1;
      }
    }
  }
}

.empty-state {
  margin-top: 120rpx;
}
</style>
